
import os, time, add_consignor, store_credit
from operator import itemgetter
from Tkinter import *

class main():
    def __init__(self, parent, root):
        self.root = root
        self.dh = parent.dh
        self.parent = parent
        self.reportPath = parent.reportPath
        self.boothPath = parent.boothPath
        self.storeCreditPath = parent.storeCreditPath
        self.root.title('Totals Due to Consignors')
        self.cons_num = StringVar()
        self.cons_list = []
        self.timestamp = time.localtime()
        
        self.mainframe = Frame(self.root,padx=20,pady=20 ) 
        self.mainframe.grid(column=0, row=0, sticky = (N, W, E ,S))
        self.mainframe.columnconfigure(0, weight=1)
        self.mainframe.rowconfigure(0, weight=1)
        
        self.totalOwedAll = StringVar()
        self.totalOwedAll.set('Total owed to consignors: $0.00')
        
        totalLabel = Label(self.mainframe,textvariable = self.totalOwedAll).grid(row=0,column=0)       
        self.consList = Listbox(self.mainframe,width=80,height=30)
        self.consList.grid(row=3,column=0)
        self.consList.bind('<Double-Button-1>',self.editAmount)
        self.consList.bind('<Return>',self.editAmount)  
        doneButton = Button(self.root,text=' Done ', command=self.finalize).grid(row=4,column=1,sticky=E)
        self.populateAll()
        
    def populateAll(self):
        total = 0.
        writeList = []
        for key in self.dh.cons_dict.keys():
            cons = self.dh.cons_dict[key]
            total += float(cons.last_owed_amount)
            writeList.append([cons.reversed_name,cons.last_owed_amount,cons.last_owed_comments,cons])
               
        self.cons_list = []        
        self.totalOwedAll.set('Total owed to consignors: $%.2f' % total)
        reportName = os.path.join(self.reportPath,'%s_%s_ConsignorTotals.csv' % (self.timestamp.tm_mon,self.timestamp.tm_year))
        f = open(reportName, 'w')
        for consignor_total in sorted(writeList, key = itemgetter(0)):
            insText = '%s -       $%s  %s' % (consignor_total[0],consignor_total[1],consignor_total[2])
            if float(consignor_total[1]) != 0:
                self.consList.insert(END,insText)
                self.cons_list.append(consignor_total[-1])
            f.writelines(insText+'\n')            
        f.close()
                
    def editAmount(self,event=None):
        top = Toplevel()
        anchors = self.consList.curselection()
        for anchor in anchors:
            cons_num = self.cons_list[anchor].number
            add_screen=add_consignor.main(self.parent,top)
            add_screen.num.set(cons_num)
            add_screen.readConsignorNum()
            self.root.wait_window(add_screen.root)
            self.consList.delete(anchor)
            self.populateAll()
        
    def finalize(self):
        self.root.destroy()
                
def start(parent,root):
        
    ins = main(parent,root)               
